package ltu.temp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class HtmlReader {
	
	public LtuTempEntity readHtml(){
		
		String[] currentTemp = null;
	  	String[] maxTemp = null;
	  	String[] minTemp = null;
		
		try {
     	    // Create a URL for the desired page	
       HttpClient client = new DefaultHttpClient();
       HttpGet request = new HttpGet();
       request.setURI(new URI("http://marge.campus.ltu.se/temp/"));
       HttpResponse response = client.execute(request);
       BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
     	 	
     	    // Read all the text returned by the server
     	   // BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
     	      
     	    String htmlLine;
     	    String htmlPage = null;
     	    
     	    int i = 0;
     	    while((htmlLine = in.readLine()) != null) {
     	    i++;
     	    if (i == 20){
     	    	currentTemp = htmlLine.split(" ");  	
     	    }
     	    if (i == 22){
     	    	maxTemp = htmlLine.split(" "); 	
     	    }
     	    if (i == 23){
     	    	minTemp = htmlLine.split(" "); 
     	    }
     	      
     	    }
     	    
    
    String currentTimeString = new SimpleDateFormat("HH:mm").format(new Date());
            
    in.close();
    return new LtuTempEntity(currentTemp[9],currentTimeString,maxTemp[19],maxTemp[14],minTemp[19],minTemp[14]); 
     	} 
  	catch (MalformedURLException e) { Log.d("message", e.toString());} 
  	catch (IOException e) { Log.d("message", e.toString());}
  	catch (URISyntaxException e) {Log.d("message", e.toString());}
  	catch (IllegalStateException e) {Log.d("message", e.toString());}
		
		return null;
		
	}

}
